<template>
  <!-- <div @click="showDate = true">{{ showName }}<van-icon name="arrow-down" class="d-mg-l5" /></div> -->
  <SelectBlock @click="showDate = true" :text="showName"></SelectBlock>
  <van-popup v-model:show="showDate" round position="bottom" :teleport="body">
    <van-date-picker v-model="date" @cancel="showDate = false" @confirm="onConfirm" :columns-type="dateType.split(',')"
      :formatter="formatter" :max-date="maxDate">
      <template #title>
        <van-dropdown-menu>
          <van-dropdown-item v-model="dateType" :options="dateTypeOption" />
        </van-dropdown-menu>
      </template>
    </van-date-picker>
  </van-popup>
</template>

<script setup>

import { onMounted, ref, watch } from 'vue'
import SelectBlock from '../basic-components/SelectBlock.vue'

/** 弹出框的 title 中，有一个按年、按月切换的下拉 */


const props = defineProps(['modelValue'])
const emits = defineEmits(['update:modelValue', 'confirm'])
const maxDate = ref(null);

const body = document.body

const showDate = ref(false)
const date = ref([''])
const dateType = ref('year,month')

const dateTypeOption = ref([{
  text: '按月',
  value: 'year,month'
},
{
  text: '按年',
  value: 'year'
}
])

const cy = (new Date()).getFullYear() + ''
const cm = ('0' + ((new Date()).getMonth() + 1)).slice(-2)
const currentYm = [cy, cm]
const showName = ref([`${cy}年`, `${cm}月`].join(''))

const onConfirm = value => {
  showName.value = value.selectedOptions.map(d => d.text).join('')
  showDate.value = false
  const modelValue = value.selectedValues.join('-')
  emits('update:modelValue', modelValue)
  emits('confirm', modelValue)
}

const resetDate = () => {
  date.value = dateType.value === 'year,month' ? currentYm : currentYm.slice(0, 1)
}

const formatter = (type, option) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  return option;
}

watch(dateType, val => {
  resetDate()
}, {
  immediate: true
})

onMounted(() => {
  const today = new Date();
  maxDate.value = today; // 设置 maxDate 为当前日期
});

</script>

<style lang="scss" scoped></style>